#encoding=utf8
'''
Created on 2012-9-21

@author: Administrator
'''
from Processor import Processor
from PISClass import PISClass
from models.User import User
from models.UserModel import *
from pub import Func, UserDict
from pub.Config import Config

class ULClass(Processor):
    '''
    指令：UL(user login)
    备注：用户登录
    格式：cmd #cmdID#result#userID#userName#msg
    '''
    def __init__(self,):
        Processor.__init__(self,)
        self.__outdata=None
        self.__field = {}
    def dataValidtor(self,cmdContent):
        if (len(cmdContent)==2):
            
            self.__field["userName"] = cmdContent[0]
            self.__field["userPass"] = cmdContent[1]
            return True;
        return False;
    def login(self,):
        '''
        用户登陆操作
        '''
        loginState = Config.I_USER_NOT_FOUND
        Func.debugInfo(self.__field)
        cUser = UserDict.getUserFromUserDictByUserName(self.__field["userName"])
        Func.debugInfo(cUser)
        returnValue = ()
        if cUser:
            cUser.set_socket(self._sockObj);
            self.__outdata = cUser
            if(self.__field["userPass"]==cUser.get_user_pass()):                
                returnValue =  (Config.I_USER_LOGIN_OK,cUser)
            else:
                returnValue =  (Config.I_USER_PASSWORD_ERROR,cUser)
        else:
            mUser = UserModel()
            result = mUser.checkLogin(self.__field["userName"], self.__field["userPass"])
            if(result[0]==Config.I_USER_LOGIN_OK):
                cUser = result[1]
                cUser.set_socket(self._sockObj)
                cUser.set_user_is_online(Config.I_USER_STATE_ONLINE);
                cUser.set_user_state(Config.I_USER_GAME_STATE_INIT);
                UserDict.addToUserDict(cUser)
                self.__outdata = cUser
                returnValue = (result[0],cUser)
            else:
                returnValue = (result[0],None)
        return returnValue

    def outData(self):
        '''
        输出执行结果集
        '''
        (LoginState,cUser) = self.login()
        result = Config.I_SYS_ZERO
        UserId = 0
        UserName = self.__field["userName"]
        if LoginState==Config.I_USER_LOGIN_OK:
            result = Config.I_SYS_ONE
            UserId = self.__outdata.get_user_id()
            UserName = self.__outdata.get_user_name()
        sock = self._sockObj
        Command = "%s#%s#%s#%s#%s#%s"
        CommandData = (self._cmd,
                       self._cmdId,result,
                       UserId,
                       UserName,
                       LoginState
        )
        Command = Command % CommandData
        print Command
        self._sockObj.sendLine(str(Command))
        if LoginState==Config.I_USER_LOGIN_OK:
            tmp = PISClass()
            tmp.getData(Config.CommandMap["PIS"][0], 0, [UserId,0,"",""], self._sockObj)
            tmp.outData()
        return Config.I_SYS_ONE;